package com.mgzf.sdk.conf.configuration;

import com.mgzf.sdk.util.MogoAESUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * Created by mike on 18/1/19.
 */
@Configuration
public class SdkConfConfiguration {
    public static Properties properties;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertieSources() {
        PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer() {
            @Override
            protected Properties mergeProperties() throws IOException {
                Properties props = super.mergeProperties();
                //TODO 此处可对 配置文件加密解密操作

                String url = props.getProperty("jdbc.url");

                int x = url.indexOf("&amp;");
                if (x != -1) {
                    url = url.replace("&amp;", "&");
                }

                if (url != null) {
                    //解密jdbc.password属性值，并重新设置
                    props.setProperty("jdbc.url", url);
                }
                String password = props.getProperty("jdbc.password");
                if (password != null) {
                    //解密jdbc.password属性值，并重新设置
                    props.setProperty("jdbc.password", MogoAESUtil.decrypt(password));
                }
                String userName = props.getProperty("jdbc.username");
                if (userName != null) {
                    //解密jdbc.userName属性值，并重新设置
                    props.setProperty("jdbc.username", MogoAESUtil.decrypt(userName));
                }
                SdkConfConfiguration.properties = props;
                return properties;
            }

        };
        List<Resource> resources = new ArrayList<Resource>();
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

            List<Resource> resourceList = Arrays.asList(resolver.getResources("classpath:/conf/*.properties"));
            if (!org.springframework.util.CollectionUtils.isEmpty(resourceList)) {
                resources.addAll(resourceList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        ppc.setLocations(resources.toArray(new Resource[]{}));
        return ppc;
    }
}
